package lyx.tank.element
{
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Matrix;
	import flash.geom.Point;
	
	import lyx.game.control.IKeyControlTarget;
	import lyx.game.locator.ElementLocator;
	import lyx.game.utils.Direction;
	import lyx.game.utils.KeySetting;
	import lyx.game.utils.KeyState;
	import lyx.math.geometry.PanelGeometry;

	public class PlayerTank extends Tank implements IKeyControlTarget
	{
		private var _player_tank_view_datas:Array;
		
		public function PlayerTank(x:int=0, y:int=0)
		{
			super(x, y,0xd69812);
			type = "PlayerTank";
		}
		
		public function actionByKeysState(state:KeyState,keyset:KeySetting):void
		{
			var direction_keys:Array = [keyset.up,keyset.down,keyset.left,keyset.right];
			if(direction_keys.indexOf(state.last_keycode)!=-1)
			{
				steps = 0;
				var direction_actions:Array = state.getKeysInArray(direction_keys);
				if(direction_actions.length>0)
				{
					steps = 1;
					var direction_key:int = direction_actions.pop() as int;
					switch(direction_key)
					{
						case keyset.up:
							direction = Direction.NORTH;
							break;
						case keyset.down:
							direction = Direction.SOUTH;
							break;
						case keyset.left:
							direction = Direction.WEST;
							break;
						case keyset.right:
							direction = Direction.EAST;
							break;
					}
				}
			}
			else if(state.last_is_keydown)
			{
				switch(state.last_keycode)
				{
					case keyset.action_0:
						var bullet:Bullet = fire();
						if(bullet!=null)
						{
							ElementLocator.GAME_ELEMENTS.push(bullet);
						}
						break;
				}
			}
		}
		
		override public function fire():Bullet
		{
			var bullet:Bullet = super.fire();
			if(bullet!=null)
			{
				bullet.face_style = 0x339911;
			}
			return bullet;
		}
		
		override public function move(time:int):void
		{
			var old_steps:int = steps;
			super.move(time);
			steps = old_steps;
		}
		
		override protected function updateViewContext():void
		{
			if(_player_tank_view_datas==null)
			{
				_player_tank_view_datas = [];
				var graphics_face:Sprite = new Sprite();
				var directions:Array = [Direction.EAST,Direction.SOUTH,Direction.WEST,Direction.NORTH];
				for(var i:int=0;i<directions.length;i++)
				{
					graphics_face.graphics.clear();
					graphics_face.graphics.beginFill(face_style);
					graphics_face.graphics.drawRect(0,0,40,40);
					
					var point:Point = PanelGeometry.rotatePoint(Math.PI*(directions[i]+2)/4,new Point(20,5),new Point(20,20));
					
					graphics_face.graphics.beginFill(0x888888);
					graphics_face.graphics.drawCircle(point.x,point.y,5);
					graphics_face.graphics.endFill();
					
					_player_tank_view_datas[directions[i]] = new BitmapData(40,40,true,0);
					_player_tank_view_datas[directions[i]].draw(graphics_face);
				}
			}
			
			view_data = _player_tank_view_datas[_direction];
		}
		
	}
}